package org.yan.kangaroo.auth.config.security.handler;

import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.yan.kangaroo.auth.config.security.SecurityUserDetails;
import org.yan.kangaroo.auth.config.security.token.EmailVerifyCodeAuthenticationToken;
import org.yan.kangaroo.auth.service.UserLoginHistoryService;
import org.yan.kangaroo.auth.util.JwtUtils;
import org.yan.kangaroo.common.response.ResponseUtils;
import org.yan.kangaroo.common.response.Result;
import org.yan.kangaroo.common.util.JsonUtils;
import org.yan.kangaroo.common.util.ip.IpInfoResult;
import org.yan.kangaroo.common.util.ip.IpLocationInfoResultVO;
import org.yan.kangaroo.common.util.ip.IpUtils;
import org.yan.kangaroo.pojo.ucenter.constant.UserAuthIdentityTypeEnum;
import org.yan.kangaroo.pojo.ucenter.entity.UserLoginHistory;

/**
 * 验证成功登录处理
 *
 * @author wangx
 * @date 11/08/2019 23:08
 */
@Slf4j
@Component
public class McpAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Value("${tencent.location.key}")
    private String key;

    @Autowired
    private UserLoginHistoryService userLoginHistoryService;

    @Override
    public void onAuthenticationSuccess(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Authentication authentication) {
        SecurityUserDetails userDetails = (SecurityUserDetails) authentication.getPrincipal();
        log.info("[onAuthenticationSuccess] 登录成功:{}", JsonUtils.getInstance().toJson(userDetails));
        UserLoginHistory userLoginHistory = new UserLoginHistory();
        userLoginHistory.setAccountId(userDetails.getAccountId());
        if (authentication instanceof EmailVerifyCodeAuthenticationToken) {
            userLoginHistory.setLoginMethod(UserAuthIdentityTypeEnum.EMAIl.getType());
        }
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            userLoginHistory.setLoginMethod(UserAuthIdentityTypeEnum.USERNAME.getType());
        }
        userLoginHistory.setStatus(Boolean.TRUE);
        String ip = IpUtils.getIpAddress(request);
        userLoginHistory.setIp(ip);
        String originUserAgent = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(originUserAgent);
        userLoginHistory.setUserAgent(originUserAgent);
        userLoginHistory.setBrowser(userAgent.getBrowser().getName());
        userLoginHistory.setOperatorSystem(userAgent.getOperatingSystem().getName());
        IpLocationInfoResultVO ipLocationInfoResultVO = IpUtils.getIpAddressInfo(ip, key);
        if (ipLocationInfoResultVO == null) {
            log.info("[onAuthenticationSuccess] 登录位置信息获取失败");
            userLoginHistoryService.localLoginInsert(userLoginHistory);
        } else {
            log.info("[onAuthenticationSuccess] 登录位置信息获取成功");
            IpInfoResult result = ipLocationInfoResultVO.getResult();
            userLoginHistory.setNation(result.getAdInfo().getNation());
            userLoginHistory.setProvince(result.getAdInfo().getProvince());
            userLoginHistory.setCity(result.getAdInfo().getCity());
            userLoginHistory.setDistrict(result.getAdInfo().getDistrict());
            userLoginHistory.setAdcode(Integer.parseInt(result.getAdInfo().getAdcode()));
            userLoginHistory.setLat(result.getLocation().getLat());
            userLoginHistory.setLng(result.getLocation().getLng());
            userLoginHistoryService.insert(userLoginHistory);
        }
//        List<String> authorities = new ArrayList<>();
//        List<SimpleGrantedAuthority> grantedAuthorities = (List<SimpleGrantedAuthority>) userDetails.getAuthorities();
//        if (CollectionUtils.isNotEmpty(grantedAuthorities)) {
//            grantedAuthorities.forEach(grantedAuthority -> authorities.add(grantedAuthority.getAuthority()));
//        }
        String token = JwtUtils.createToken(userDetails);
        ResponseUtils.outAsJson(response, Result.ok(token));
    }
}
